<template>
  <div class="app-container">
    <!--查询条件表单-->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="家长编号" prop="familyCode">
        <el-input v-model="queryParams.familyCode" placeholder="请输入家长编号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="家长编码" prop="familyEng">
        <el-input v-model="queryParams.familyEng" placeholder="请输入家长编码" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="家长名称" prop="familyName">
        <el-input v-model="queryParams.familyName" placeholder="请输入家长名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="家长状态" clearable>
          <el-option v-for="dict in sys_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!--按钮操作区-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermission="['school:family:add']"
        >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermission="['school:family:edit']"
        >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermission="['school:family:remove']"
        >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermission="['school:family:export']"
        >导出</el-button
        >
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!--数据表格区-->
    <el-table v-loading="loading" :data="familyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="家长ID" align="center" prop="familyId" />
      <el-table-column label="头像" align="center" prop="avatar" width="60">
        <template #default="scope">
          <img :src="prefixAvatar(scope.row.avatar)" class="user-avatar"/>
        </template>
      </el-table-column>
      <!--      <el-table-column label="家长编号" align="center" prop="familyCode" />-->
      <!--      <el-table-column label="家长编码" align="center" prop="familyEng" />-->
      <el-table-column label="家长名称" align="center" prop="familyName" />
      <el-table-column label="账号" align="center" prop="account" />
      <el-table-column label="性别" align="center" prop="sexStr" />
      <el-table-column label="出生日期" align="center" prop="birthDay" />
      <el-table-column label="手机号" align="center" prop="cellPhone" />
<!--      <el-table-column label="邮箱" align="center" prop="email" width="180" />-->
            <el-table-column label="微信号" align="center" prop="wechat" />
      <!--      <el-table-column label="QQ号" align="center" prop="qq" />-->
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="406" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
              link
              type="primary"
              icon="User"
              @click="handleRelation(scope.row)"
              v-hasPermission="['school:family:relation']"
          >学生</el-button
          >
          <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermission="['school:family:edit']"
          >修改</el-button
          >
          <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermission="['school:family:remove']"
          >删除</el-button
          >
          <el-button
              link
              type="primary"
              icon="Key"
              @click="handleResetPwd(scope.row)"
              v-hasPermission="['system:family:resetPwd']"
          >重置密码</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--表格分页-->
    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!--关联学生对话框-->
    <el-dialog :title="relationTitle" v-model="relationOpen" width="600px" append-to-body>
      <el-form ref="familyStudentRef" :model="relationForm" :rules="relationRules" label-width="80px">
        <el-row>
          <el-col :span = "24">
            <el-form-item label="学生家长" prop="familyName">
              <el-input v-model="relationForm.familyName" disabled  placeholder="请输入学生家长" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
           <el-col :span="12">
             <el-form-item label="年级" prop="gradeId">
               <el-select v-model="relationForm.gradeId" @change="gradeChangeHandle" placeholder="请选择">
                 <el-option
                     v-for="item in gradeOptions"
                     :key="item.gradeId"
                     :label="item.gradeName"
                     :value="item.gradeId"
                     :disabled="item.status == 0"
                 ></el-option>
               </el-select>
             </el-form-item>
           </el-col>
          <el-col :span="12">
            <el-form-item label="班级" prop="clazzId">
              <el-select v-model="relationForm.clazzId" @change="clazzChangeHandle"  placeholder="请选择">
                <el-option
                    v-for="item in clazzOptions"
                    :key="item.clazzId"
                    :label="item.clazzName"
                    :value="item.clazzId"
                    :disabled="item.status == 0"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
            <el-col :span="12">
              <el-form-item label="学生" prop="studentId">
                <el-select v-model="relationForm.studentId"   placeholder="请选择">
                  <el-option
                      v-for="item in studentOptions"
                      :key="item.studentId"
                      :label="item.studentName"
                      :value="item.studentId"
                      :disabled="item.status == 0"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          <el-col :span="12">
            <el-form-item label="关系" prop="knownRelation">
            <el-select v-model="relationForm.knownRelation" placeholder="与学生关系">
              <el-option v-for="dict in sys_family_relation" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="relationForm.status">
                <el-radio v-for="dict in sys_status" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="补充关系" prop="unknownRelation">
              <el-input v-model="relationForm.unknownRelation" placeholder="请输入补充关系"  />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="relationForm.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-table v-loading="relationLoading" :data="familyStudentList">
              <el-table-column label="关系ID" align="center" prop="familyStudentId" />
              <el-table-column label="关系" align="center" prop="knownRelationStr" />
              <el-table-column label="年级" align="center" prop="gradeName" />
              <el-table-column label="班级" align="center" prop="clazzName" />
              <el-table-column label="学生" align="center" prop="studentName" />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                  <el-button
                      link
                      type="primary"
                      icon="Delete"
                      @click="handleRelationDelete(scope.row)"
                      v-hasPermission="['school:family_student:remove']"
                  >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="relationSubmitForm">确 定</el-button>
          <el-button @click="relationCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改家长类型对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="familyRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="家长编号" prop="familyCode">
              <el-input-number v-model="form.familyCode" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="家长编码" prop="familyEng">
              <el-input v-model="form.familyEng" placeholder="请输入家长编码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="家长名称" prop="familyName">
              <el-input v-model="form.familyName" placeholder="请输入家长名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in sys_status" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <!--额外字段-->
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="form.familyId == undefined"  label="账号" prop="account">
              <el-input v-model="form.account" placeholder="请输入登录账号" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.familyId == undefined"  label="密码" prop="password">
              <el-input
                  v-model="form.password"
                  placeholder="请输入登录密码"
                  type="password"
                  maxlength="20"
                  show-password
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="用户性别" prop="sex">
              <el-select v-model="form.sex" placeholder="请选择">
                <el-option
                    v-for="dict in sys_user_sex"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birthDay">
              <el-date-picker
                  v-model="form.birthDay"
                  value-format="YYYY-MM-DD"
                  type="date"
                  placeholder="请选择出生日期"
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="cellPhone">
              <el-input v-model="form.cellPhone" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="微信号" prop="wechat">
              <el-input v-model="form.wechat" placeholder="请输入微信号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="QQ号" prop="qq">
              <el-input v-model="form.qq" placeholder="请输入QQ号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="家庭住址" prop="address">
              <el-input v-model="form.address" placeholder="请输入家庭住址" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="个人头像" >
              <el-upload
                  ref="upload"
                  class="avatar-uploader"
                  action="javascript:void(0);"
                  :show-file-list="false"
                  :auto-upload="false"
                  :on-change="onChange"
                  accept="image/*"
              >
                <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <img :src="imageUrl" class="avatar" />
          </el-col>
        </el-row>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="Family">
import {ref, reactive, toRefs, getCurrentInstance, watch} from "vue";
import * as familyApi from "@/api/school/familyApi";
import * as familyStudentApi from "@/api/school/familyStudentApi";
import * as publicApi from "@/api/school/publicApi";
import defAva from '@/assets/images/profile.jpg';
import {prefixAvatar} from "@/utils/common";
import * as studentApi from "@/api/school/studentApi";

/** 公共变量 */
const { proxy } = getCurrentInstance();
const { sys_status, sys_user_sex, sys_family_relation } = proxy.useDict('sys_status', 'sys_user_sex', 'sys_family_relation');
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    familyCode: undefined,
    familyEng: undefined,
    familyName: undefined,
    status: undefined,
  },
  form: {
    familyCode: undefined,
    familyEng: undefined,
    familyName: undefined,
    status: 1,
    account: undefined,
    password: undefined,
    sex: undefined,
    birthDay: undefined,
    cellPhone: undefined,
    email: undefined,
    wechat: undefined,
    qq: undefined,
    address: undefined,
    remark: undefined,
    avatar: undefined,
  },
  relationForm: {
    familyId: undefined,
    familyName: undefined,
    gradeId: undefined,
    clazzId: undefined,
    studentId: undefined,
    knownRelation: undefined,
    unknownRelation: undefined,
    status: 1,
    remark: undefined
  },
  rules: {
    familyCode: [{ required: true, message: '家长编号不能为空', trigger: 'blur' }],
    familyEng: [{ required: true, message: '家长编码不能为空', trigger: 'blur' }],
    familyName: [{ required: true, message: '家长名称不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
    sex: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
    birthDay: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
    account: [
      { required: true, message: '账号不能为空', trigger: 'blur' },
      {
        min: 2,
        max: 20,
        message: '账号长度必须介于 2 和 20 之间',
        trigger: 'blur',
      },
    ],
    password: [
      { required: true, message: '密码不能为空', trigger: 'blur' },
      {
        min: 5,
        max: 20,
        message: '密码长度必须介于 5 和 20 之间',
        trigger: 'blur',
      },
    ],
    email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
    cellPhone: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }],
  },
  relationRules: {
    familyId: [{ required: true, message: '家长不能为空', trigger: 'blur' }],
    studentId: [{ required: true, message: '学生不能为空', trigger: 'blur' }],
    knownRelation: [{ required: true, message: '二者关系不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
  }
})

const { queryParams, form, rules, relationForm, relationRules } = toRefs(data)


/** 查询表单相关变量 */
const showSearch = ref(true);


/** 表格相关变量*/
const loading = ref(true);
const familyList = ref([]);
const relationLoading = ref(true);
const familyStudentList = ref([]);
const total = ref(0);

/** 按钮操作区相关变量 */
const single = ref(true);
const multiple = ref(true);
const open = ref(false);
const title = ref('');
const ids = ref([]);
const imageUrl = ref(defAva);

/** 关联学生相关变量 */
const relationOpen = ref(false);
const relationTitle = ref('');
const gradeOptions = ref([]);
const clazzOptions = ref([]);
const studentOptions = ref([]);

/** 查询家长类型列表 */
function getList() {
  loading.value = true;
  familyApi
      .listFamily(queryParams.value)
      .then((response) => {
        familyList.value = response.rows;
        total.value = response.total;
      })
      .finally(() => {
        loading.value = false;
      });
}
getList();

function getFamilyStudentList(familyId) {
  relationLoading.value = true;
  familyStudentApi
      .listFamilyStudent({familyId})
      .then((response) => {
        familyStudentList.value = response;
      })
      .finally(() => {
        relationLoading.value = false;
      });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef');
  handleQuery();
}

/** 表单重置 */
function reset() {
  form.value = {
    familyId: undefined,
    familyCode: undefined,
    familyEng: undefined,
    familyName: undefined,
    status: 1,
    account: undefined,
    password: undefined,
    sex: undefined,
    birthDay: undefined,
    cellPhone: undefined,
    email: undefined,
    wechat: undefined,
    qq: undefined,
    address: undefined,
    remark: undefined,
    avatar: undefined,
  };
  imageUrl.value = defAva
  proxy.resetForm('familyRef');
}

/** 关联学生表单重置 */
function relationReset() {
  relationForm.value = {
    familyStudentId: undefined,
    familyId: undefined,
    familyName: undefined,
    gradeId: undefined,
    clazzId: undefined,
    studentId: undefined,
    knownRelation: undefined,
    unknownRelation: undefined,
    status: 1,
    remark: undefined
  };
  proxy.resetForm('familyStudentRef');
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = '添加家长';
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const familyId = row.familyId || ids.value;
  familyApi.getFamily(familyId).then((response) => {
    if(response.avatar != undefined) {
      imageUrl.value = import.meta.env.VITE_APP_BASE_API + response.avatar
    }
    form.value = response;
    open.value = true;
    title.value = '修改家长';
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const familyIds = row.familyId || ids.value;
  proxy.$modal
      .confirm(`是否确认删除家长ID为"${familyIds}"的数据项？`)
      .then(() => familyApi.deleteFamily(familyIds))
      .then(() => {
        getList();
        proxy.$modal.msgSuccess('删除成功');
      })
      .catch(() => {});
}

function handleRelationDelete(row) {
  const familyStudentIds = row.familyStudentId || ids.value;
  proxy.$modal
      .confirm(`是否确认删除关系ID为"${familyStudentIds}"的数据项？`)
      .then(() => familyStudentApi.deleteFamilyStudent(familyStudentIds))
      .then(() => {
        getFamilyStudentList(relationForm.value.familyId);
        proxy.$modal.msgSuccess('删除成功');
      })
      .catch(() => {});
}

/** 关联学生按钮操作 */
function handleRelation(row) {
  relationReset();
  const familyId = row.familyId || ids.value;
  familyApi.getFamily(familyId).then((response) => {
    relationForm.value.familyName = response.familyName
    relationForm.value.familyId = response.familyId
    relationOpen.value = true;
    relationTitle.value = '家长学生关联';
  });
  getFamilyStudentList(familyId)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
      'school/family/export',
      {
        ...queryParams.value,
      },
      `family_${new Date().getTime()}.xlsx`,
  );
}


/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.familyId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs.familyRef.validate((valid) => {
    if (valid) {
      if (form.value.familyId != undefined) {
        familyApi.updateFamily(form.value).then((response) => {
          proxy.$modal.msgSuccess('修改成功');
          open.value = false;
          getList();
        });
      } else {
        familyApi.addFamily(form.value).then((response) => {
          proxy.$modal.msgSuccess('新增成功');
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

publicApi.allGradeList().then((response) => {
  gradeOptions.value = response
})

watch(
    () => data.relationForm.gradeId,
    (newValue, oldValue) => {
      console.log("newValue",newValue, "oldvalue", oldValue);
      if (newValue === undefined || newValue == null) {
        data.relationForm.clazzId = undefined
      } else {
        publicApi.allClazzList({gradeId : newValue}).then((response) => {
          clazzOptions.value = response
        })
      }
    }
);

function gradeChangeHandle(gradeId) {
  console.log(gradeId)
  data.relationForm.clazzId = undefined
}

function clazzChangeHandle(clazzId) {
  publicApi.allStudentList({clazzId}).then((response) => {
    studentOptions.value = response
  })
}

function relationSubmitForm() {
  proxy.$refs.familyStudentRef.validate((valid) => {
    if (valid) {
      familyStudentApi.addFamilyStudent(relationForm.value).then((response) => {
        proxy.$modal.msgSuccess('新增成功');
        relationOpen.value = false;
        getList();
      });
    }
  });
}

function relationCancel() {
  relationOpen.value = false;
  relationReset();
}

/** 重置密码按钮操作 */
function handleResetPwd(row) {
  proxy
      .$prompt(`请输入"${row.familyName}"的新密码`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: '用户密码长度必须介于 5 和 20 之间',
      })
      .then(({ value }) => {
        familyApi.resetFamilyPassword(row.familyId, value).then((response) => {
          proxy.$modal.msgSuccess(`修改成功，新密码是：${value}`);
        });
      })
      .catch(() => {});
}

function onChange(file) {
  console.log("ddd")
  const formData = new FormData();
  formData.append('file', file.raw);
  studentApi.uploadAvatar(formData).then((response) => {
    console.log(response)
    imageUrl.value = import.meta.env.VITE_APP_BASE_API + response.fileName
    form.value.avatar = response.fileName
  })
}


</script>

<style scoped>
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.user-avatar {
  width: 40px;
  height: 40px;
  display: block;
  border-radius: 20px;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.el-form-item__label {
  font-weight: 700;
}
</style>
